import React, { useEffect, useState, useRef } from "react";
import { Table, Image, Button, Popconfirm } from "antd";
import { getBannerListInterface, delBannerInterface } from "@/api/banner";
import usePagination from "@/hooks/usePagination";
import { DeleteOutlined, InfoCircleOutlined } from "@ant-design/icons";

export default function List() {
  const [dataSource, setDataSource] = useState([]);
  const pagination = usePagination();
  const flagRef = useRef(true);

  const getBannerList = () => {
    getBannerListInterface().then((res) => setDataSource(res?.data?.data));
  };
  useEffect(() => {
    getBannerList();
  }, []);
  // 监测是否翻页,对序号标识进行判断修改
  useEffect(() => {
    flagRef.current = true;
  }, [pagination]);
  // 删除单条轮播图数据
  const delBanner = (record) => {
    delBannerInterface({ bannerid: record.bannerid }).then((res) => {
      getBannerList();
    });
  };
  return (
    <Table
      dataSource={dataSource}
      rowKey={(record) => record.bannerid}
      pagination={pagination}
    >
      <Table.Column
        title="序号"
        render={(_, __, index) => {
          // 判断删除的是否为最后一页页最后一条数据
          dataSource?.length ===
            pagination.pageSize * (pagination.current - 1) &&
            (flagRef.current = false);
          return (
            pagination.pageSize *
              (flagRef.current
                ? pagination.current - 1
                : pagination.current - 2) +
            index +
            1
          );
        }}
      />
      <Table.Column
        title="图片"
        dataIndex="img"
        render={(text) => {
          return <Image src={text} style={{ height: "100px" }}></Image>;
        }}
      />
      <Table.Column title="link" dataIndex="link" />
      <Table.Column title="alt" dataIndex="alt" />
      <Table.Column
        title="操作"
        render={(_, record) => {
          return (
                   <Popconfirm
              title="不可逆操作!"
              description="你确定要删除该条数据吗?"
              icon={<InfoCircleOutlined style={{ color: "red" }} />}
              onConfirm={() => {
                 delBanner(record);
                getBannerList()
              }}
            >
              <Button type="primary" danger icon={<DeleteOutlined />} shape="circle"/>
            </Popconfirm>
          );
        }}
      />
    </Table>
  );
}
